<?php

namespace App\Http\Controllers\Admin;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use DB;

class FriendurlController extends Controller
{
    // 链接列表
	public function friendurl_list()
	{
		$friendurls = DB::table('friendurl')->orderBy('id','desc')->paginate(20);
		return view('admin/friendurl_list',['friendurls'=>$friendurls]); 
	}
	
	// 添加列表
	public function friendurl_add(Request $request)
	{
		if($request->isMethod('post')){
			$lname = $request->input('lname','','htmlspecialchars');
			$url = $request->input('url');
			$sort = $request->input('sort');
			if(empty($lname)) return redirect('/prompt')->with(['message'=>'链接名不能为空','url' =>'/admin/friendurl_add', 'jumpTime'=>3,'status'=>'error']);
			if(!preg_match('/\b(([\w-]+:\/\/?|www[.])[^\s()<>]+(?:\([\w\d]+\)|([^[:punct:]\s]|\/)))/',$url)) return redirect('/prompt')->with(['message'=>'链接格式错误','url' =>'/admin/friendurl_add', 'jumpTime'=>3,'status'=>'error']);
			# 插入数据
			$res = DB::table('friendurl')->insert(['lname'=>$lname,'url'=>$url,'sort'=>$sort]);
			if($res){
				return redirect('friendurl_list');
			} else {
				return redirect('/prompt')->with(['message'=>'添加失败，请联系客服','url' =>'/admin/friendurl_add', 'jumpTime'=>3,'status'=>'error']);
			}
		}
		return view('admin/friendurl_add');
	}
	
	// 修改列表
	public function friendurl_edit(Request $request,$id)
	{
		if(!preg_match('/^[1-9]\d*$/',$id)) return redirect('/prompt')->with(['message'=>'参数错误','url' =>'/admin/friendurl_list', 'jumpTime'=>3,'status'=>'error']);
		# 查询内容
		$friendurl = DB::table('friendurl')->where('id',$id)->select('lname','id','url','sort')->first();
		if($request->isMethod('post')){
			$lname = $request->input('lname','','htmlspecialchars');
			$url = $request->input('url');
			$sort = $request->input('sort');
			if(empty($lname)) return redirect('/prompt')->with(['message'=>'链接名不能为空','url' =>'/admin/friendurl_add', 'jumpTime'=>3,'status'=>'error']);
			if(!preg_match('/\b(([\w-]+:\/\/?|www[.])[^\s()<>]+(?:\([\w\d]+\)|([^[:punct:]\s]|\/)))/',$url)) return redirect('/prompt')->with(['message'=>'链接格式错误','url' =>'/admin/friendurl_add', 'jumpTime'=>3,'status'=>'error']);
			# 更新数据
			$res = DB::table('friendurl')->where('id',$id)->update(['lname'=>$lname,'url'=>$url,'sort'=>$sort]);
			if($res){
				return redirect('friendurl_list');
			} else {
				return redirect('/prompt')->with(['message'=>'更新失败，请联系客服','url' =>'/admin/friendurl_edit/'.$id, 'jumpTime'=>3,'status'=>'error']);
			}
		}
		return view('admin/friendurl_edit',['friendurl'=>$friendurl]);
	}
	
	// 删除列表
	public function friendurl_del(Request $request)
	{
		if($request->isMethod('post')){
			$id = $request->input('id');
			if(!preg_match('/^[1-9]\d*$/',$id)) json_return(1000,'参数错误');
			
			# 删除数据
			$res = DB::table('friendurl')->where('id',$id)->delete();
			if($res){
				json_return(200,'删除成功');
			} else {
				json_return(1000,'删除失败');
			}
		}
	}
	
	
	
}
